﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="MiscResources.cs" company="" />
// <summary>
//   Maintains ad-hoc resources such as embedded bitmaps.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace FormsUtilities
{
    using System;
    using System.Collections.Generic;
    using System.Drawing;
    using System.Reflection;

    using Utilities;

    /// <summary>
    /// Maintains ad-hoc resources such as embedded bitmaps.
    /// </summary>
    public static class MiscResources
    {
        /// <summary>
        /// A cache for images based on their containing assembly qualified name and their representing resource name.
        /// </summary>
        private static readonly Dictionary<Tuple<string, string>, Image> s_imagesMap = new Dictionary<Tuple<string, string>, Image>();

        /// <summary>
        /// Retrieves an image from within a given assembly, by its given name, and caches the image for later use.
        /// </summary>
        /// <param name="containerAssembly"></param>
        /// <param name="resourceName"></param>
        /// <returns></returns>
        public static Image GetImage(Assembly containerAssembly, string resourceName)
        {
            var imageKey = new Tuple<string, string>(containerAssembly.FullName, resourceName);

            if (s_imagesMap.ContainsKey(imageKey))
            {
                return s_imagesMap[imageKey];
            }

            var image = Image.FromStream(AssemblyInfo.GetEmbeddedObjectStream(containerAssembly, resourceName));

            s_imagesMap.Add(imageKey, image);
            return image;
        }
    }
}
